<script lang="ts" setup>
import { getToken } from "@/utils/cache/cookies"
import { ElMessage, UploadInstance } from "element-plus"
import { ref } from "vue"

const props = defineProps({
  btnText: {
    type: String,
    default: "导入表格"
  },
  tip: {
    type: String
  },
  path: {
    type: String
  },
  data: {
    type: Object
  },
  handleSuccess: {
    type: Function,
    default() {
      return () => {}
    }
  },
  modelValue: String
})

const emit = defineEmits(["update:modelValue"])

const handleBeforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isLt10M) {
      ElMessage.error("上传文件大小不能超过 10MB!")
      reject()
    }
  })
}

const handleChange = async (file: any) => {
  emit("update:modelValue", file.raw)
}
const uploadRef = ref<UploadInstance>()
const submitUpload = async () => {
  await uploadRef.value!.submit()
}
defineExpose({ submitUpload })
const headers = { Authorization: "Bearer " + getToken() }
</script>

<template>
  <el-upload
    :value="props.modelValue"
    ref="uploadRef"
    class="upload-demo"
    :action="path"
    :data="data"
    :limit="1"
    :before-update="handleBeforeUpload"
    :on-change="handleChange"
    :auto-upload="false"
    :headers="headers"
    :on-success="handleSuccess"
  >
    <el-button>{{ btnText }}</el-button>
  </el-upload>
</template>
